﻿using System;

using CalciumTemplateApp.Views.Options.UserOptionViews;

using Outcoder;
using Outcoder.UserOptionsModel;

using Xamarin.Forms;

namespace CalciumTemplateApp.Views.Options
{
    public class OptionTemplateSelector : ViewCell
    {
	    public OptionTemplateSelector()
	    {
		    BindingContextChanged += HandleBindingContextChanged;
	    }

	    void HandleBindingContextChanged(object sender, EventArgs eventArgs)
	    {
			var context = BindingContext;

			if (context == null)
			{
				View = null;
				return;
			}

		    var parent = Parent;
			if (parent != null && parent.BindingContext == context)
			{
				return;
			}

		    var userOption = ((IUserOptionReaderWriter)context).UserOption;
		    if (userOption == null)
		    {
			    throw new Exception("Expected binding context to include a UserOption.");
		    }

			string templateName = userOption.TemplateName;

		    View newView = null;

		    if (templateName == "Boolean")
		    {
			    newView = Dependency.Resolve<BooleanView>();
		    }
		    else if (templateName == "String")
		    {
				newView = Dependency.Resolve<StringView>();
		    }
		    else
		    {
			    Type viewType = Type.GetType(templateName, false);
			    if (viewType == null)
			    {
				    throw new Exception("Unable to resolve template with name: " + templateName);
			    }
		    }

		    View = newView;
	    }
    }
}
